<template>
  <view class="records-container">
    <!-- 统计卡片 -->
    <view class="stat-cards">
      <view class="stat-card green-card">
        <view class="stat-icon">
          <uni-icons type="checkbox-filled" size="24" color="#52c41a"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.passed }}</view>
          <view class="stat-label">通过</view>
        </view>
      </view>
      <view class="stat-card yellow-card">
        <view class="stat-icon">
          <uni-icons type="eye-filled" size="24" color="#faad14"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.inspected }}</view>
          <view class="stat-label">已抽检</view>
        </view>
      </view>
      <view class="stat-card blue-card">
        <view class="stat-icon">
          <uni-icons type="calendar-filled" size="24" color="#1890ff"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.today }}</view>
          <view class="stat-label">今日查验</view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-filter">
      <view class="search-box">
        <uni-search-bar 
          v-model="searchValue" 
          placeholder="搜索商户名称或预约编号" 
          @confirm="handleSearch"
          @clear="handleClear"
          cancel-button="none"
        ></uni-search-bar>
      </view>
      <view class="filter-row">
        <picker mode="date" :value="filterDate" @change="handleDateChange">
          <view class="filter-item">
            <uni-icons type="calendar" size="16" color="#666"></uni-icons>
            <text>{{ filterDate || '选择日期' }}</text>
            <uni-icons type="bottom" size="12" color="#999"></uni-icons>
          </view>
        </picker>
        <picker :range="statusOptions" range-key="label" @change="handleStatusChange">
          <view class="filter-item">
            <uni-icons type="list" size="16" color="#666"></uni-icons>
            <text>{{ currentStatusLabel }}</text>
            <uni-icons type="bottom" size="12" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
    </view>

    <!-- 记录列表 -->
    <scroll-view 
      scroll-y 
      class="list-container"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="list.length > 0">
        <view v-for="item in list" :key="item.checkId" class="record-item" @click="goToDetail(item)">
          <view class="item-header">
            <view class="item-info">
              <view class="merchant-name">{{ item.merchantName }}</view>
              <view class="apply-no">预约编号：{{ item.applyNo }}</view>
            </view>
            <view :class="['qr-badge', getQrColorClass(item.qrColor)]">
              {{ getQrColorText(item.qrColor) }}
            </view>
          </view>
          
          <view class="item-content">
            <view class="content-row">
              <view class="content-item">
                <text class="item-label">查验时间：</text>
                <text class="item-value">{{ formatDateTime(item.checkTime) }}</text>
              </view>
            </view>
            <view class="content-row">
              <view class="content-item">
                <text class="item-label">入场地点：</text>
                <text class="item-value">{{ item.entryPlace }}</text>
              </view>
              <view class="content-item">
                <text class="item-label">车牌号：</text>
                <text class="item-value">{{ item.vehicleNo }}</text>
              </view>
            </view>
            <view v-if="item.checkStatus === '1' && item.inspectionItems" class="inspection-info">
              <uni-icons type="info-filled" size="14" color="#faad14"></uni-icons>
              <text>抽检商品：{{ item.inspectionItems }}</text>
            </view>
          </view>
          
          <view class="item-footer">
            <view class="checker-info">
              <uni-icons type="person" size="14" color="#999"></uni-icons>
              <text>查验人：{{ item.checkUserName || '系统' }}</text>
            </view>
            <view :class="['status-tag', getStatusClass(item.checkStatus)]">
              {{ getStatusText(item.checkStatus) }}
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else-if="!loading" class="empty-state">
        <image src="/static/images/empty.png" class="empty-image"></image>
        <text class="empty-text">暂无查验记录</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading && list.length > 0" class="loading-more">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { listCheckRecords, getCheckStatistics } from '@/api/business/check.js'

export default {
  data() {
    return {
      searchValue: '',
      filterDate: '',
      currentStatus: '',
      statusOptions: [
        { label: '全部状态', value: '' },
        { label: '已通过', value: '0' },
        { label: '需抽检', value: '1' },
        { label: '已拒绝', value: '2' }
      ],
      list: [],
      loading: false,
      refreshing: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      statistics: {
        passed: 0,
        inspected: 0,
        today: 0
      }
    }
  },
  computed: {
    currentStatusLabel() {
      const option = this.statusOptions.find(item => item.value === this.currentStatus)
      return option ? option.label : '全部状态'
    }
  },
  onLoad() {
    this.loadStatistics()
    this.loadList(true)
  },
  methods: {
    // 加载统计数据
    async loadStatistics() {
      try {
        const res = await getCheckStatistics()
        if (res.code === 200) {
          this.statistics = res.data || {
            passed: 0,
            inspected: 0,
            today: 0
          }
        }
      } catch (error) {
        console.error('加载统计失败:', error)
      }
    },
    
    // 加载列表
    async loadList(refresh = false) {
      if (this.loading) return
      if (!refresh && !this.hasMore) return
      
      this.loading = true
      if (refresh) {
        this.pageNum = 1
        this.hasMore = true
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        // 添加筛选条件
        if (this.searchValue) {
          params.keyword = this.searchValue
        }
        if (this.filterDate) {
          params.checkDate = this.filterDate
        }
        if (this.currentStatus !== '') {
          params.checkStatus = this.currentStatus
        }
        
        const res = await listCheckRecords(params)
        
        if (res.code === 200) {
          const data = res.rows || []
          const total = res.total || 0
          
          if (refresh) {
            this.list = data
          } else {
            this.list = [...this.list, ...data]
          }
          
          this.hasMore = this.list.length < total
          if (this.hasMore) {
            this.pageNum++
          }
        } else {
          if (refresh) {
            this.list = []
          }
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        if (refresh) {
          this.list = []
        }
        this.hasMore = false
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadStatistics()
      this.loadList(true)
    },
    
    // 加载更多
    loadMore() {
      this.loadList()
    },
    
    // 搜索
    handleSearch() {
      this.loadList(true)
    },
    
    // 清空搜索
    handleClear() {
      this.searchValue = ''
      this.loadList(true)
    },
    
    // 日期筛选
    handleDateChange(e) {
      this.filterDate = e.detail.value
      this.loadList(true)
    },
    
    // 状态筛选
    handleStatusChange(e) {
      const index = e.detail.value
      this.currentStatus = this.statusOptions[index].value
      this.loadList(true)
    },
    
    // 跳转详情
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/check/detail?id=${item.checkId}&applyId=${item.applyId}`
      })
    },
    
    // 获取二维码颜色样式
    getQrColorClass(color) {
      const map = {
        '0': 'green-qr',
        '1': 'yellow-qr',
        '2': 'red-qr'
      }
      return map[color] || ''
    },
    
    // 获取二维码颜色文本
    getQrColorText(color) {
      const map = {
        '0': '绿码',
        '1': '黄码',
        '2': '红码'
      }
      return map[color] || ''
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const map = {
        '0': 'status-passed',
        '1': 'status-inspect',
        '2': 'status-rejected'
      }
      return map[status] || ''
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        '0': '已通过',
        '1': '需抽检',
        '2': '已拒绝'
      }
      return map[status] || ''
    },
    
    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return ''
      return datetime.replace('T', ' ').substring(0, 16)
    }
  }
}
</script>

<style scoped>
.records-container {
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 统计卡片 */
.stat-cards {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.stat-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.green-card .stat-icon {
  background: rgba(82, 196, 26, 0.1);
}

.yellow-card .stat-icon {
  background: rgba(250, 173, 20, 0.1);
}

.blue-card .stat-icon {
  background: rgba(24, 144, 255, 0.1);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 搜索筛选 */
.search-filter {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 2rpx;
}

.search-box {
  margin-bottom: 20rpx;
}

.filter-row {
  display: flex;
  gap: 20rpx;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #333;
}

/* 列表 */
.list-container {
  height: calc(100vh - 400rpx);
  padding: 0 20rpx;
}

.record-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.item-info {
  flex: 1;
}

.merchant-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.apply-no {
  font-size: 24rpx;
  color: #999;
}

.qr-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.green-qr {
  background: linear-gradient(135deg, #f6ffed, #d4f8d4);
  color: #52c41a;
}

.yellow-qr {
  background: linear-gradient(135deg, #fffbe6, #fff1b8);
  color: #faad14;
}

.red-qr {
  background: linear-gradient(135deg, #fff1f0, #ffccc7);
  color: #ff4d4f;
}

.item-content {
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
}

.content-row {
  display: flex;
  margin-bottom: 12rpx;
}

.content-row:last-child {
  margin-bottom: 0;
}

.content-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.item-label {
  font-size: 24rpx;
  color: #999;
}

.item-value {
  font-size: 24rpx;
  color: #333;
}

.inspection-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 12rpx;
  padding: 12rpx;
  background: #fffbe6;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #8b7355;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.checker-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 24rpx;
  color: #999;
}

.status-tag {
  padding: 6rpx 16rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-passed {
  background: #f6ffed;
  color: #52c41a;
}

.status-inspect {
  background: #fffbe6;
  color: #faad14;
}

.status-rejected {
  background: #fff1f0;
  color: #ff4d4f;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  opacity: 0.6;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
  margin-top: 30rpx;
}

.loading-more {
  padding: 30rpx;
  text-align: center;
}
</style>